package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entity.CommonResult;
import com.atguigu.springcloud.entity.Payment;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/consumer")
public class OrderController {
    private final RestTemplate restTemplate;
//    private static final String PAYMENT_URL = "http://localhost:8001";
    private static final String PAYMENT_URL = "http://cloud-payment-service";
    public OrderController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @GetMapping("/payment/create")
    public CommonResult<Payment> create(Payment payment) {
//        return  restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
        ParameterizedTypeReference<CommonResult<Payment>> typeReference = new ParameterizedTypeReference<>() {};
        return restTemplate.exchange(PAYMENT_URL + "/payment/create", HttpMethod.POST, new HttpEntity<>(payment), typeReference).getBody();
    }

    @GetMapping("/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Integer id) {
//        return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
        ParameterizedTypeReference<CommonResult<Payment>> typeReference = new ParameterizedTypeReference<>() {};
        return restTemplate.exchange(PAYMENT_URL + "/payment/get/" + id, HttpMethod.GET, null, typeReference).getBody();
    }

    @GetMapping("/payment/discovery")
    public Object discovery() {
        return restTemplate.getForObject(PAYMENT_URL + "/payment/discovery", Object.class);
    }
}
